<?php

namespace App\Containers\AppSection\Moneybox\Actions;

use App\Containers\AppSection\Moneybox\Tasks\GenerateUuidAndIdTask;
use App\Ship\Exceptions\BadRequestException;
use App\Ship\Parents\Actions\Action;
use Exception;
use GuzzleHttp\Client;

class TransferMoneyAction extends Action
{
    protected Client $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    /**
     * @throws Exception
     */
    public function run()
    {
        $data = app(GenerateUuidAndIdTask::class)->run();
        try {
            $body = [
                'jsonrpc' => '2.0',
                'method' => 'transfer_money',
                'id' => $data['uuid'],
                'params' => [
                    "recipient_account" => config('appSection-moneybox.account'),
                    "recipient_bank_code" => config('appSection-moneybox.transfer_money_bik'),
                    "amount" => 100000,
                    "purpose" => "Оплата по договору 12345"
                ],
            ];

            $response = $this->client->post(config('appSection-moneybox.transfer_money_url'), [
                'json' => $body,
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                ],
            ]);

            $contents = $response->getBody()->getContents();
            if (!empty($contents)) {
                $resp = json_decode($contents);
                if (!empty($resp->error)){
                    throw new BadRequestException($resp->error->message);
                }
            }

        } catch (\Throwable $e) {
            $exception = "";
            if (method_exists($e, 'hasResponse')) {
                $exception = (string)$e->getResponse()->getBody();
            }
            throw new Exception($exception, $e->getCode());
        }
    }
}
